package org.advanced.aqs;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author John.zhang
 * @version Id: Semaphores, v 1.0 2020/12/10 17:05 ZhiYong Exp $
 * 限流控制，队列如果满的那么就阻塞
 */
public class Semaphores {

    public static void main(String[] args) {
        //当前可以获得的最大许可数
        Semaphore semaphore = new Semaphore(5);
        int max = 10;
        for (int i = 0; i < max; i++) {
            new Car(i,semaphore).start();
        }
    }

    static class Car extends Thread {
        private int num;
        private Semaphore semaphore;

        public Car(int num, Semaphore semaphore) {
            this.num = num;
            this.semaphore = semaphore;
        }

        @Override
        public void run() {
            try {
                semaphore.acquire();//获得一个许可
                System.out.println(num + "占用");
                TimeUnit.SECONDS.sleep(2);
                System.out.println(num + "离开");
                semaphore.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }


}
